package com.document.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class URLFilter implements Filter{

	private final String HOMEPAGE = "/login";
	
	private String except_urlpattern = "";
	
	private final String INIT_PARAMETER = "_except_urlpattern";
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String url = httpRequest.getRequestURI();
		String path = httpRequest.getContextPath();
		String suffix = getUrlSuffix(url);
		System.out.println(url);
		if(except_urlpattern.indexOf(suffix) == -1){
			if(url.equals(path + HOMEPAGE)){
				httpRequest.getSession().setAttribute("logined",true);
				chain.doFilter(httpRequest,httpResponse);
				return;
			}else{
				Object obj = (httpRequest.getSession().getAttribute("logined"));
				if(obj == null || !(Boolean)obj){
//					request.getRequestDispatcher("index.html").forward(httpRequest, response);
					httpResponse.sendRedirect(path  + "/index.html");
					return;
				}else{
					chain.doFilter(httpRequest,httpResponse);
					return;
				}
			}
		}else{
			chain.doFilter(httpRequest,httpResponse);
			return;
		}
	}

	public void init(FilterConfig config) throws ServletException {
		except_urlpattern = config.getInitParameter(INIT_PARAMETER);		
	}
	
	private String getUrlSuffix(String url){
		String suffix = "";
		int index = url.lastIndexOf(".");
		if( index != -1){
			suffix = url.substring(index);
		}
		return suffix;
	}
}
